package com.yuyou.train.user.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;  import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.yuyou.train.service.api.admin.service.CommDataConfigAPI;
import com.yuyou.train.service.api.lesson.dto.ResourceDetailDTO;
import com.yuyou.train.service.api.lesson.dto.UserClassDTO;
import com.yuyou.train.service.api.lesson.dto.UserLessonTreeDTO;
import com.yuyou.train.service.api.lesson.dto.UserLessonTreeHwDTO;
import com.yuyou.train.service.api.lesson.entity.Lesson;
import com.yuyou.train.service.api.lesson.entity.LessonClass;
import com.yuyou.train.service.api.lesson.entity.LessonResourceRuleRelation;
import com.yuyou.train.service.api.lesson.entity.ResourceExam;
import com.yuyou.train.service.api.lesson.entity.ResourceExamItem;
import com.yuyou.train.service.api.lesson.entity.ResourceQuestion;
import com.yuyou.train.service.api.lesson.entity.Rule;
import com.yuyou.train.service.api.lesson.service.ExamAPI;
import com.yuyou.train.service.api.lesson.service.LessonAPI;
import com.yuyou.train.service.api.lesson.service.QuestionAPI;
import com.yuyou.train.service.api.lesson.service.ResourceAPI;
import com.yuyou.train.service.api.lesson.service.RuleAPI;
import com.yuyou.train.service.api.user.entity.User;
import com.yuyou.train.service.api.user.entity.UserDynamic;
import com.yuyou.train.service.api.user.entity.UserHw;
import com.yuyou.train.service.api.user.entity.UserLessonProgress;
import com.yuyou.train.service.api.user.entity.UserThoughts;
import com.yuyou.train.user.mapper.UserLessonProgressMapper;
import com.yuyou.train.user.service.IUserCommentService;
import com.yuyou.train.user.service.IUserDataConfigService;
import com.yuyou.train.user.service.IUserDynamicService;
import com.yuyou.train.user.service.IUserHwBeService;
import com.yuyou.train.user.service.IUserHwPraiseService;
import com.yuyou.train.user.service.IUserHwService;
import com.yuyou.train.user.service.IUserHwTeacherService;
import com.yuyou.train.user.service.IUserLessonProgressBehaService;
import com.yuyou.train.user.service.IUserLessonProgressService;
import com.yuyou.train.user.service.IUserPointsService;
import com.yuyou.train.user.service.IUserPraiseService;
import com.yuyou.train.user.service.IUserService;
import com.yuyou.train.user.service.IUserThoughtsService;
import com.yuyou.train.user.service.IUserTotalService;
import com.yuyou.train.user.vo.UserLessonProgressVideoVO;
import com.yuyou.train.user.vo.req.ReqBehavior;
import com.yuyou.train.user.vo.req.ReqBehaviorExam;
import com.yuyou.train.user.vo.req.ReqBehaviorQuestion;
import com.yuyou.train.user.vo.resp.RespGetLessonContent;
import com.yuyou.train.user.vo.resp.RespGetLessonExam;
import com.yuyou.train.user.vo.resp.RespGetLessonExamAns;
import com.yuyou.train.user.vo.resp.RespGetLessonExamComp;
import com.yuyou.train.user.vo.resp.RespNextLessonContent;
import com.yuyou.train.util.bean.ResBoolSimpleInfo;
import com.yuyou.train.util.constant.lesson.LessonCons;
import com.yuyou.train.util.constant.user.UserLessonProgressCons;
import com.yuyou.train.util.enums.CommEnums;
import com.yuyou.train.util.enums.lesson.LessonEnums;
import com.yuyou.train.util.enums.lesson.QuestionEnums;
import com.yuyou.train.util.enums.user.UserDynamicEnums;
import com.yuyou.train.util.enums.user.UserEnums;
import com.yuyou.train.util.enums.user.UserHwEnums;
import com.yuyou.train.util.enums.user.UserLessonProgressEnums;
import com.yuyou.train.util.message.CommMess;
import com.yuyou.train.util.message.lesson.LessonMess;
import com.yuyou.train.util.message.user.UserDynamicMess;
import com.yuyou.train.util.message.user.UserHwMess;
import com.yuyou.train.util.message.user.UserLessonProMess;
import com.yuyou.train.util.tool.DefindBeanUtils;
import com.yuyou.train.util.tool.HtmlUtils;
import com.yuyou.train.util.tool.MathUtils;
import com.yuyou.train.util.tool.RedisLockUtil;
import com.yuyou.train.util.tool.Sequence;

@Service
public class UserLessonProgressServiceImpl implements IUserLessonProgressService {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private UserLessonProgressMapper useLesProMapper;

	@Autowired
	private IUserService userService;
	
	@Autowired
	private IUserDataConfigService userDataConfigService;
	
	@Autowired
	private IUserHwService userHwService;
	
	@Autowired
	private IUserHwPraiseService userHwPraiseService;
	
	@Autowired
	private IUserHwBeService userHwBeService;
	
	@Autowired
	private IUserThoughtsService userThoughtsService;
		
	@Autowired
	private IUserPointsService userPointsService;
	
	@Autowired
	private CommDataConfigAPI commDataConfigAPI;
	
	@Autowired
	private RuleAPI ruleAPI;
	
	@Autowired
	private ResourceAPI resourceAPI;
	
	@Autowired
	private LessonAPI lessonAPI;
	
	@Autowired
	private QuestionAPI questionAPI;
	
	@Autowired
	private ExamAPI examAPI;
	
	@Autowired
	private IUserPraiseService userPraiseService;
	
	@Autowired
	private IUserCommentService userCommentService;
	
	@Autowired
	private IUserHwTeacherService userHwTeacherService;
	
	@Autowired
	private IUserLessonProgressBehaService userLesProBehService;
	
	@Autowired
	private IUserDynamicService userDynamicService;
	
	@Autowired
	private IUserTotalService userTotalService;
	
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	@Override
	public int deleteByPrimaryKey(String id) {
		return useLesProMapper.deleteByPrimaryKey(id);
	}

	@Override
	public int insert(UserLessonProgress record) {
		record.setId(Sequence.getSequence().getNextId());
		record.setCreateTime(new Date());
		record.setUpdateTime(new Date());
		return useLesProMapper.insert(record);
	}

	@Override
	public UserLessonProgress selectByPrimaryKey(String id) {
		return useLesProMapper.selectByPrimaryKey(id);
	}

	@Override
	public int updateByPrimaryKeySelective(UserLessonProgress record) {
		record.setUpdateTime(new Date());
		return useLesProMapper.updateByPrimaryKeySelective(record);
	}

	/**
	 * 学员当前学习课程（1：null，为开始学习。2：lessonId（能通过lesson表查）。3：lessonId为1，结果页面（不能通过lesson表查））
	 */
	@Override
	public UserLessonProgress getUserCurrLesson(String userId,String classId) {
		return useLesProMapper.getUserCurrLesson(userId,classId);
	}

		
	@Override
	@Transactional(timeout=60)
	public ResBoolSimpleInfo<RespNextLessonContent> openUserNextLessonLock(
			String userId,String subjectId,ReqBehavior reqBehavior,boolean ignore)throws Exception{
		
		return openUserNextLesson(userId,subjectId,reqBehavior,ignore);
//		ResBoolSimpleInfo<RespNextLessonContent> res=new ResBoolSimpleInfo<RespNextLessonContent>();
//		String pre=CommEnums.lockClass.OPEN_USER_NEXT.getValue();
//		boolean b=RedisLockUtil.tryLock(userId, pre);
//		if(b){
//			try{
//				return openUserNextLesson(userId,subjectId,reqBehavior,ignore);
//			}catch(Exception e ){
//				logger.error("",e);
//				res.setMessage(e.getMessage());
//				res.setSuccess(false);
//				return res;
//			}finally{
//				RedisLockUtil.unLock(userId, pre);
//			}
//		}else{
//			res.setSuccess(false);
//			res.setMessage("获取锁失败");
//			return res;
//		}	
	}
	
	@Override
	@Transactional(timeout=60)
	public ResBoolSimpleInfo<RespNextLessonContent> openUserNextLesson(String userId,String subjectId,ReqBehavior reqBehavior,boolean ignore)throws Exception {
		ResBoolSimpleInfo<RespNextLessonContent> res=new ResBoolSimpleInfo<RespNextLessonContent>();
		
		User user=userService.selectByPrimaryKey(userId);	
		if(user.getType().equals(UserEnums.type.teacher.getValue())){
			res.setSuccess(false);
			res.setMessage(CommMess.ERR_POWER);
			return res;
		}
		
		//当前班级为禁用中，不能过关
		LessonClass _class=lessonAPI.findLessonClassById(user.getClassId());
		if(_class.getIsUse().equals(CommEnums.isUse.no.getValue())){
			res.setSuccess(false);
			res.setMessage(UserLessonProMess.ERR_LESSON_CLASS_DISABLE);
			return res;
		}
		
		
		//用户状态毕业和未通过时候直接返回，审核状态结果页处理
		if(user.getLearnStatus().equals(UserEnums.learnStatus.graduation.getValue())||
				user.getLearnStatus().equals(UserEnums.learnStatus.fail.getValue())){
			res.setSuccess(false);
			res.setMessage(UserLessonProMess.ERR_USER_LESSON_END);
			return res;
		}	
		
		//当前课程
		UserLessonProgress currProgress=this.getUserCurrLesson(user.getId(),user.getClassId());
		if(currProgress==null || ignore){
			//为空就是还没开始
			return insertUserNextLesson(user,subjectId);
		}
		//作业，等待老师审批
		else if(currProgress.getStatus().equals(UserLessonProgressEnums.status.Auditing.getValue())
				&& !currProgress.getResourceType().equals(CommEnums.resourceType.exam.getValue())
				){
			res.setSuccess(false);
			res.setMessage(UserLessonProMess.ERR_USER_LESSON_AUDING);
			return res;
		}
		//等待班级考核不能过关其他课程
		else if(user.getLearnStatus().equals(UserEnums.learnStatus.waiting.getValue())&&
				!currProgress.getLessonId().equals(UserLessonProgressCons.END_LESSON_ID1)){
			res.setSuccess(false);
			res.setMessage(UserLessonProMess.ERR_USER_LESSON_WAITING);
			return res;
		}
		else{
			//判断是否过关，更新当前进度状态
			res=solveRule(user,currProgress,reqBehavior);
			if(res.isSuccess()){
				//完成课程，插入动态
				Lesson lesson=lessonAPI.selectLessonById(currProgress.getLessonId());
				if(lesson !=null){
					//为空是结果页
					//统计用户数据
					userTotalService.updateLessonTotal(user, lesson);
					return insertUserNextLesson(user,null);
				}				

			}	
		}		
		return res;
	}
	
	
	@Transactional(timeout=60)
	public ResBoolSimpleInfo<RespNextLessonContent> insertUserNextLesson(User user,String subjectId) throws Exception{
			
		ResBoolSimpleInfo<RespNextLessonContent> res=new ResBoolSimpleInfo<RespNextLessonContent>();
		
		//获取下一个课程，是否已完成所有课程
		if(StringUtils.isEmpty(subjectId)){
			subjectId=userDataConfigService.selectUserSubjectId(user.getId());
		}
		String nextLessonId=this.getUserNextLesson(user.getClassId(),user.getId(),subjectId);
		
		if(!StringUtils.isEmpty(nextLessonId)){
			Lesson nextLesson=lessonAPI.selectLessonById(nextLessonId);
			//当前的课程主键
			LessonResourceRuleRelation lesResoRulRel=lessonAPI.selectLessonRelByLessonId(nextLessonId);	
			//资源
			ResourceDetailDTO resource=resourceAPI.selectById(lesResoRulRel.getResourceId());			
			String resourceType=resource.getResourceType();	
			
			UserLessonProgress pro=new UserLessonProgress();	
			pro.setUserId(user.getId());
			pro.setLessonId(nextLessonId);
			pro.setStatus(UserLessonProgressEnums.status.studying.getValue());
			pro.setSort(nextLesson.getSort());
			pro.setClassId(user.getClassId());
			pro.setResourceType(resourceType);
			pro.setLessonResourceRuleRelationId(lesResoRulRel.getId());
			pro.setIsAttr(nextLesson.getAttr());
			this.insert(pro);
				
			res.setData(new RespNextLessonContent(nextLessonId,resourceType));
			res.setSuccess(true);
			
		}else if(!user.getLearnStatus().equals(UserEnums.learnStatus.waiting.getValue())){
			//完成所有课程，触发毕业证书
			User upUser=new User();
			upUser.setId(user.getId());
			upUser.setLearnStatus(UserEnums.learnStatus.waiting.getValue());
			userService.updateByPrimaryKeySelective(upUser);
			
			UserLessonProgress pro=new UserLessonProgress();	
			pro.setUserId(user.getId());
			pro.setLessonId(UserLessonProgressCons.END_LESSON_ID1);
			pro.setStatus(UserLessonProgressEnums.status.studying.getValue());
			pro.setSort(Long.valueOf(UserLessonProgressCons.END_LESSON_ID1));
			pro.setClassId(user.getClassId());
			pro.setResourceType("");
			pro.setLessonResourceRuleRelationId("");
			pro.setIsAttr(LessonEnums.attr.comm.getValue());
			this.insert(pro);
			
			res.setData(new RespNextLessonContent(UserLessonProgressCons.END_LESSON_ID1,""));
			res.setSuccess(true);
		}		
		return res;
	}
	
	

		
	public ResBoolSimpleInfo<RespNextLessonContent> solveRule(User user,UserLessonProgress currProgress,ReqBehavior reqBehavior) throws Exception{			
		ResBoolSimpleInfo<RespNextLessonContent> res=new ResBoolSimpleInfo<RespNextLessonContent>();
		UserLessonProgress updateProgress=new UserLessonProgress();
		
			//如果是结果页,保存用户班级点评
			if(currProgress.getLessonId().equals(UserLessonProgressCons.END_LESSON_ID1) && !user.getLearnStatus().equals(UserEnums.learnStatus.trainning.getValue())){
				ResBoolSimpleInfo<String> resEnd=userLesProBehService.solveEnd(user, currProgress, reqBehavior);
				if(!resEnd.isSuccess()){
					res.setSuccess(false);
					res.setMessage(resEnd.getMessage());
					return res;
				}else{
					res.setSuccess(true);
					return res;
				}
			}	
			
			if(StringUtils.isEmpty(user.getParentId())){
				res.setSuccess(false);
				res.setMessage(UserLessonProMess.ERR_TEACHER_EMPTY);
				return res;
			}
			
			Lesson lesson=lessonAPI.selectLessonById(currProgress.getLessonId());
			//课程已删除直接返回
			if(lesson.isDel()){
				res.setSuccess(false);
				res.setMessage(UserLessonProMess.ERR_END_LESSON_LOST);
				return res;
			}
			
			//判断规则是否通过		
			LessonResourceRuleRelation rel= lessonAPI.selectLessonRelByLessonId(currProgress.getLessonId());		

			//一个课程只有一个资源只有一个规则
			Rule rule=ruleAPI.selectById(rel.getRuleId());
			//资源
			ResourceDetailDTO resource=resourceAPI.selectById(rel.getResourceId());			
			String resourceType=rule.getResourceType();				
			updateProgress.setResourceType(resourceType);
			
			
			//数据校验
			ResBoolSimpleInfo<String> resVal=ReqBehavior.validate(resourceType, reqBehavior);
			if(!resVal.isSuccess()){
				res.setSuccess(false);
				res.setMessage(resVal.getMessage());
				return res;
			}
			
			if(resourceType.equals(CommEnums.resourceType.video.getValue())){				
				//视频规则（请求就通过）	
				long duration=Math.round(reqBehavior.getVideo().getDuration());				
				UserLessonProgressVideoVO u=new UserLessonProgressVideoVO(reqBehavior.getVideo().getDuration());
				//保存行为结果
				updateProgress.setResult(JSON.toJSONString(u));
				
				//统计用户数据
				userTotalService.updateVideoTotal(user.getId(), duration);
				
				userDynamicService.addUserDynamic(new UserDynamic(user.getId(),user.getClassId(),currProgress.getLessonId(),
						currProgress.getLessonId(),String.format(UserDynamicMess.CONTENT, user.getUsername(),lesson.getName()),UserDynamicEnums.type.lesson.getValue(),currProgress.getResourceType()));
			}
			else if(resourceType.equals(CommEnums.resourceType.music.getValue())){}
			else if(resourceType.equals(CommEnums.resourceType.file.getValue())){}
			else if(resourceType.equals(CommEnums.resourceType.exam.getValue())){
				
				ReqBehaviorExam reqExam=reqBehavior.getExam();							
				List<ReqBehaviorQuestion> myAnsList=reqExam.getMyAns();			
				ResourceExam resourceExam=examAPI.selectExamById(resource.getResourceExamId());
				
				RespGetLessonExam resp=new RespGetLessonExam();
				resp.setExamName(resourceExam.getName());
				resp.setExamTime(reqExam.getExamTime());
				resp.setNum(resourceExam.getNum());
				resp.setResourceExamId(resourceExam.getId());
				resp.setScore(resourceExam.getScore());
				resp.setSeconds(resourceExam.getSeconds());
				resp.setHeadImg(user.getHeadImg());
				
				List<RespGetLessonExamAns> ansDetail=new ArrayList<RespGetLessonExamAns>();
				List<Boolean> ansSimple=new ArrayList<Boolean>();
				
				//重做试卷
				if(reqExam.isRepeatExam()){
					//更新当前进度状态
					updateProgress.setId(currProgress.getId());
					updateProgress.setStatus(UserLessonProgressEnums.status.studying.getValue());
					updateProgress.setResult(StringUtils.EMPTY);
					res.setSuccess(false);
					this.updateByPrimaryKeySelective(updateProgress);	
					return res;
				}
				
				//过关分数
				int score=rule.getNeedScore()==null?0:rule.getNeedScore();
				//算分数
				int sum=0;
				int rightNum=0;
				for(ReqBehaviorQuestion ans:myAnsList){
					ResourceExamItem item=examAPI.selectExamItemById(ans.getItemId());				
					ResourceQuestion question=questionAPI.selectQuestionById(item.getResourceQuestionId());
					if(checkExamQues(ans.getAnsList(),question.getAnswer(),question.getQuestionType())){
						rightNum++;
						sum=sum+item.getScore();
						ansSimple.add(true);
					}else{
						ansSimple.add(false);
					}					
					//保存记录
					RespGetLessonExamAns ansDetailTemp=new RespGetLessonExamAns();
					ansDetailTemp.setBody(question.getBody());
					JSONArray jsonArr=JSON.parseArray(question.getAnswer());
					ansDetailTemp.setRightAns(jsonArr);
					ansDetailTemp.setMyAns(ans.getAnsList());
					ansDetailTemp.setQuestionType(question.getQuestionType());
					ansDetailTemp.setAnswerConfig(question.getAnswerConfig());
					ansDetailTemp.setItemId(item.getId());
					ansDetail.add(ansDetailTemp);
					
				}
				resp.setAnsSimple(ansSimple);
				resp.setAnsDetail(ansDetail);	
				
				resp.setGetScore(sum);
				
				
				//正确率
				resp.setPer(MathUtils.div(rightNum, resourceExam.getNum(), 2));	
				
				if(sum>=score){
					//试卷通过
					updateProgress.setStatus(UserLessonProgressEnums.status.finish.getValue());
					resp.setExamResult(true);	
					
					userLesProBehService.addLessonPoints(user.getId(), lesson);
					res.setSuccess(true);
				
					userDynamicService.addUserDynamic(new UserDynamic(user.getId(),user.getClassId(),currProgress.getLessonId(),
							currProgress.getLessonId(),String.format(UserDynamicMess.CONTENT, user.getUsername(),lesson.getName()),UserDynamicEnums.type.lesson.getValue(),currProgress.getResourceType()));
					
					//统计用户数据
					ResBoolSimpleInfo<String> totalRes=userTotalService.updateExamFullTotal(user.getId(), sum, resourceExam.getScore());
					resp.setMedal(totalRes.getData());
					resp.setPoints(lesson.getScore());
					
				}else{
					//试卷不通过
					updateProgress.setStatus(UserLessonProgressEnums.status.Auditing.getValue());
					resp.setExamResult(false);
					res.setMessage(UserLessonProMess.ERR_EXAM_NOT_PASS);
					res.setSuccess(false);		
				}						
				//pk人				
				List<String> pkHeadImgList=new ArrayList<String>();
				genPkPeople(pkHeadImgList,user.getId(),currProgress,resp.getExamTime(),resp.getPer());				
				resp.setPeople(pkHeadImgList);							
				//保存行为结果				
				updateProgress.setResult(JSON.toJSONString(resp));
				
				//更新当前进度状态
				updateProgress.setId(currProgress.getId());
				int operNum=currProgress.getOperNum()==null?0:currProgress.getOperNum();
				updateProgress.setOperNum(++operNum);
				this.updateByPrimaryKeySelective(updateProgress);			

				return res;
			}
			else if(resourceType.equals(CommEnums.resourceType.hwJustCommit.getValue())){				
				solveHwRule(res,updateProgress,user,currProgress,reqBehavior,rule,lesson);
				return res;				
			}
			else if(resourceType.equals(CommEnums.resourceType.hwNeedComment.getValue())){				
				solveHwRule(res,updateProgress,user,currProgress,reqBehavior,rule,lesson);
				return res;
				
			}
			else if(resourceType.equals(CommEnums.resourceType.thought.getValue())){
				
				UserThoughts userThoughts=new UserThoughts();
				userThoughts.setLessonId(currProgress.getLessonId());
				if(reqBehavior.getThought()!=null){
					userThoughts.setLearnContent(reqBehavior.getThought().getLearnContent());				
					userThoughts.setPlanContent(reqBehavior.getThought().getPlanContent());
					userThoughts.setThinkContent(reqBehavior.getThought().getThinkContent());
					userThoughts.setTitle(reqBehavior.getThought().getTitle());					
				}
				userThoughts.setUserId(user.getId());
				userThoughtsService.addUserThoughts(userThoughts);				
				userDynamicService.addUserDynamic(new UserDynamic(user.getId(),user.getClassId(),currProgress.getLessonId(),
						userThoughts.getId(),String.format(UserDynamicMess.CONTENT_THOUGHT, user.getUsername(),userThoughts.getTitle()),UserDynamicEnums.type.thought.getValue(),currProgress.getResourceType()));				
				
			}	
			
			//更新当前进度状态
			updateProgress.setId(currProgress.getId());
			updateProgress.setStatus(UserLessonProgressEnums.status.finish.getValue());
			updateProgress.setGetPoints(lesson.getScore()==null?0:lesson.getScore());
			this.updateByPrimaryKeySelective(updateProgress);	
			//添加积分
			userLesProBehService.addLessonPoints(user.getId(),lesson);
			
		res.setSuccess(true);
		return res;
	}

	public void solveHwRule(
			ResBoolSimpleInfo<RespNextLessonContent> res,
			UserLessonProgress updateProgress,
			User user,
			UserLessonProgress currProgress,
			ReqBehavior reqBehavior,
			Rule rule,		
			Lesson lesson){
		UserHw hwExist=userHwService.selectOnlyUserHwLock(user.getId(), currProgress.getLessonId());
		if(hwExist!=null){
			res.setSuccess(false);
			res.setMessage(CommMess.ERR_REAPET);
			return;
		}		
		//插入作业
		UserHw userHw=new UserHw();
		userHw.setLessionId(currProgress.getLessonId());
		userHw.setUserId(user.getId());
		userHw.setResourceType(rule.getResourceType());
		userHw.setScore(0);
		if(rule.getResourceType().equals(CommEnums.resourceType.hwJustCommit.getValue())){
			userHw.setUserAttachUrl(reqBehavior.getHwJustCommit().getUserFileUrl());
			userHw.setUserAttachName(reqBehavior.getHwJustCommit().getUserFileName());
			userHw.setFileSourceName(reqBehavior.getHwJustCommit().getFileSourceName());
		}else{
			//插入作业
			userHw.setUserAttachUrl(reqBehavior.getHwNeedComment().getUserFileUrl());
			userHw.setUserAttachName(reqBehavior.getHwNeedComment().getUserFileName());
			userHw.setFileSourceName(reqBehavior.getHwNeedComment().getFileSourceName());
		}	
		if((rule.getNeedScore()!=null&&rule.getNeedScore()>=0)){
			//由老师审批生成学生下一课					
			userHw.setStatus(UserHwEnums.hwStatus.init.getValue());
			userHwService.addUserHw(userHw);
			//是否考核节点
			if(lesson.getAttr().equals(LessonEnums.attr.check.getValue())&& rule.getResourceType().equals(CommEnums.resourceType.hwNeedComment.getValue())){
				userHwTeacherService.addTeacherUserHw(userHw.getId(), user.getClassId());
			}else{
				userHwTeacherService.addMyTeacherUserHw(userHw.getId(), user.getParentId(),"0");
			}
			
			//更新当前进度状态
			updateProgress.setId(currProgress.getId());
			updateProgress.setStatus(UserLessonProgressEnums.status.Auditing.getValue());
			
			res.setSuccess(false);
			res.setMessage(UserHwMess.CORRECTING);
		}else{
			//直接通过
			userHw.setStatus(UserHwEnums.hwStatus.pass.getValue());
			userHw.setScore(0);
			userHwService.addUserHw(userHw);
			userHwTeacherService.addMyTeacherUserHw(userHw.getId(), user.getParentId(),"1");					
			//更新当前进度状态
			updateProgress.setId(currProgress.getId());
			updateProgress.setStatus(UserLessonProgressEnums.status.finish.getValue());				
			res.setSuccess(true);
			
			userLesProBehService.addLessonPoints(user.getId(), lesson);		
			userDynamicService.addUserDynamic(new UserDynamic(user.getId(),user.getClassId(),currProgress.getLessonId(),
					userHw.getId(),String.format(UserDynamicMess.CONTENT, user.getUsername(),lesson.getName()),UserDynamicEnums.type.homework.getValue(),currProgress.getResourceType()));
		}
			
		if(rule.getResourceType().equals(CommEnums.resourceType.hwNeedComment.getValue())){
			//用户的赞踩
			if(!CollectionUtils.isEmpty(reqBehavior.getHwNeedComment().getGoodList())){
				List<String> goodList=reqBehavior.getHwNeedComment().getGoodList();
				userHwPraiseService.addHwPraiseList(goodList, userHw.getId(), UserHwEnums.hwType.student.getValue(), UserHwEnums.HwPraiseType.praise.getValue());
			}
			if(!CollectionUtils.isEmpty(reqBehavior.getHwNeedComment().getBadList())){
				List<String> badList=reqBehavior.getHwNeedComment().getBadList();
				userHwPraiseService.addHwPraiseList(badList, userHw.getId(), UserHwEnums.hwType.student.getValue(), UserHwEnums.HwPraiseType.tread.getValue());
			}
		}		
		this.updateByPrimaryKeySelective(updateProgress);	
	}
	
	
	/**
	 * 构建pk人数
	 */
	private void genPkPeople(List<String> pkHeadImgList,String userId,UserLessonProgress currProgress,int examTime,double per){
		UserLessonProgress condi=new UserLessonProgress();
		condi.setClassId(currProgress.getClassId());
		condi.setLessonId(currProgress.getLessonId());
		
		//一个月之前
		Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.MONTH, -1);
        Date m = c.getTime();
		
		condi.setUpdateTime(m);
		List<UserLessonProgress> pkList=this.findUserLessonProgress(condi);
		List<RespGetLessonExam> pkListVO=new ArrayList<RespGetLessonExam>();
		for(UserLessonProgress u:pkList){
			String examResult=u.getResult();
			if(StringUtils.isEmpty(examResult) || u.getUserId().equals(userId)){
				continue;
			}
			RespGetLessonExam vo=JSON.parseObject(examResult, RespGetLessonExam.class);
			if(per<vo.getPer()){
				continue;
			}else if(per==vo.getPer() &&  examTime>=vo.getExamTime()){
				continue;
			}		
			vo.setUserId(u.getUserId());
			pkListVO.add(vo);
		}
		RespGetLessonExamComp respGetLessonExamComp=new RespGetLessonExamComp();
		Collections.sort(pkListVO,respGetLessonExamComp);
		for(int i=0;i<pkListVO.size();i++){
			if(i==10) break;
			User u=userService.selectByPrimaryKey(pkListVO.get(i).getUserId());
			pkHeadImgList.add(u.getHeadImg());
		}
	}
	
	
	
	@Override
	public List<UserLessonTreeDTO> getUserLessonTree(String classId,
			String userId) throws Exception {
		
		String subjectId=userDataConfigService.selectUserSubjectId(userId);
		
		List<UserLessonTreeDTO> res=useLesProMapper.getUserLessonTree(classId, userId,subjectId);
		UserLessonProgress currPro=this.getUserCurrLesson(userId, classId);		
		Long currSort=currPro==null?Long.valueOf(Long.MAX_VALUE):currPro.getSort();	
		for(UserLessonTreeDTO userLesson:res){
			//处理章的情况
			if(userLesson.getUserLesSta().equals(UserLessonProgressEnums.status.donot.getValue())){
				if(userLesson.getSort()<currSort){
					userLesson.setUserLesSta(UserLessonProgressEnums.status.finish.getValue());
				}else{
					userLesson.setUserLesSta(UserLessonProgressEnums.status.lock.getValue());
				}
			}
			//试卷
			if(userLesson.getResourceType().equals(CommEnums.resourceType.exam.getValue())){				
				UserLessonProgress userLessonProgress=useLesProMapper.selectByUserIdAndLessonId(userId,userLesson.getId());
				if(userLessonProgress!=null){
					String result=userLessonProgress.getResult();
					RespGetLessonExam exam=JSON.parseObject(result,RespGetLessonExam.class);
					userLesson.setHwExamScore(exam==null?null:exam.getGetScore()==null?null:exam.getGetScore());
				}
			}
			else if(userLesson.getResourceType().equals(CommEnums.resourceType.hwNeedComment.getValue())||
					userLesson.getResourceType().equals(CommEnums.resourceType.hwJustCommit.getValue())){
				
				List<UserLessonTreeHwDTO> hwDTOList=new ArrayList<UserLessonTreeHwDTO>();
				
				UserHw condi=new UserHw();
				condi.setLessionId(userLesson.getId());
				condi.setUserId(userId);
				List<UserHw> hwList=userHwService.findUserHw(condi);
				int maxScore=0;
				for(UserHw hw:hwList){
					UserLessonTreeHwDTO hwDTO=new UserLessonTreeHwDTO();
					Long u=userCommentService.countByForeignId(hw.getId());
					hwDTO.setCommentNum(u);
					hwDTO.setContent(hw.getUserAttachName());
					hwDTO.setId(hw.getId());				
					Long p=userPraiseService.sumByForeignId(hw.getId(),"0");				
					hwDTO.setPraiseNum(p);
					hwDTO.setScore(hw.getScore());
					hwDTO.setStatus(hw.getStatus());
					hwDTO.setUpdateTime(hw.getCreateTime());
					if(hw.getScore()>maxScore){
						maxScore=hw.getScore();
					}
					hwDTOList.add(hwDTO);
				}				
				userLesson.setHwList(hwDTOList);
				userLesson.setHwExamScore(userLesson.getUserLesSta().equals(UserLessonProgressEnums.status.finish.getValue())?maxScore:null);
			}			
		}
		//结果页
		userLesProBehService.genEnd(res,userId);
		res=toLessonTreeDTO(res, null);
		
		return res;
	}
	
	@Override
	public UserLessonTreeDTO getUserchapterTree(String lessonId,
			String userId) throws Exception{
		
		UserLessonTreeDTO root=new UserLessonTreeDTO();
		String subjectId=userDataConfigService.selectUserSubjectId(userId);	
		if(lessonId.equals(UserLessonProgressCons.END_LESSON_ID1)){						
			//结果页
			root=userLesProBehService.genEndObj(UserLessonProgressEnums.status.finish.getValue());			
			UserLessonTreeDTO child=userLesProBehService.genEndLeafObj(UserLessonProgressEnums.status.studying.getValue());			
			List<UserLessonTreeDTO> childList=new ArrayList<UserLessonTreeDTO>();
			childList.add(child);
			root.setChildren(childList);			
		}else{
			//非结果页
			Lesson lesson=lessonAPI.selectLessonById(lessonId);
			Lesson pLesson=lessonAPI.selectLessonById(lesson.getParentId());	
			root.setIsLeaf(CommEnums.isLeaf.no.getValue());
			root.setId(pLesson.getId());
			root.setLevel(2);
			root.setParentId("");
			root.setName(pLesson.getName());
			root.setResourceType("");
			root.setUserLesSta(UserLessonProgressEnums.status.donot.getValue());		
			List<UserLessonTreeDTO> res=useLesProMapper.getUserchapterTree(lesson.getParentId(), userId, subjectId);
			root.setChildren(res);
		}		
		return root;
	}
	
	
	
	private List<UserLessonTreeDTO> toLessonTreeDTO(List<UserLessonTreeDTO> lessonTreeList , String parentId){
		// 返回DTO
		List<UserLessonTreeDTO> lessonTreeListRet = new ArrayList<>();
		for(UserLessonTreeDTO lessonTreeDTO : lessonTreeList){
			if(lessonTreeDTO.getParentId() == parentId || (lessonTreeDTO.getParentId() !=null && lessonTreeDTO.getParentId().equals(parentId))){
				lessonTreeListRet.add(lessonTreeDTO);
				List<UserLessonTreeDTO> children = toLessonTreeDTO(lessonTreeList, lessonTreeDTO.getId());
				lessonTreeDTO.setChildren(children);
				double sumGetMark=children.stream().mapToDouble(dto-> dto.getGetMark()==null?0:dto.getGetMark().doubleValue()).sum();
				if(sumGetMark!=0){
					lessonTreeDTO.setGetMark(new BigDecimal(sumGetMark));
				}				
			}
		}

		return lessonTreeListRet;
	}
	
	
	@Override
	public String getUserNextLesson(String classId, String userId,String subjectId)throws Exception {
		return useLesProMapper.getUserNextLesson(classId, userId, subjectId);
	}
	
	@Override
	public UserLessonProgress getUserFirstLesson(String classId, String userId)throws Exception {
		return useLesProMapper.getUserFirstLesson(classId, userId);
	}
	

	@Override
	public ResBoolSimpleInfo<RespGetLessonContent> getLessonContent(
			String userId,String loginUserId,String lessonId,String foreignId) throws Exception {
		ResBoolSimpleInfo<RespGetLessonContent> res=new ResBoolSimpleInfo<RespGetLessonContent>();
		RespGetLessonContent respOpenLessonContent=new RespGetLessonContent();	
				
		//传递用户
		User user=userService.selectByPrimaryKey(userId);
		//登录用户
		User loginUser=userService.selectByPrimaryKey(loginUserId);
		
		//如果是结果页
		if(lessonId.equals(UserLessonProgressCons.END_LESSON_ID1)){
			if(loginUser.getType().equals(UserEnums.type.teacher.getValue())){
				userLesProBehService.chooseEnd(respOpenLessonContent,user,lessonId);
			}else if(!loginUser.getLearnStatus().equals(UserEnums.learnStatus.trainning.getValue())){
				userLesProBehService.chooseEnd(respOpenLessonContent,loginUser,lessonId);
			}			
			res.setData(respOpenLessonContent);
			respOpenLessonContent.setEmpty(false);
			respOpenLessonContent.setLessonId(lessonId);
			//为空就是结果页
			respOpenLessonContent.setResourceType("");
			respOpenLessonContent.setStatus(UserLessonProgressEnums.status.studying.getValue());
			
			res.setSuccess(true);
			return res;
		}
		
		//课程的学习状态
		UserLessonProgress lessonProgress=null;
		if(loginUser.getType().equals(UserEnums.type.teacher.getValue())){
			lessonProgress=this.selectByUserIdAndLessonId(userId,lessonId);
		}else{
			
			//当前班级为禁用中，不能过关			
			LessonClass _class=lessonAPI.findLessonClassById(loginUser.getClassId());
			if(_class.getIsUse().equals(CommEnums.isUse.no.getValue())){
				res.setSuccess(false);
				res.setMessage(UserLessonProMess.ERR_LESSON_CLASS_DISABLE);
				return res;
			}
			
			lessonProgress=this.selectByUserIdAndLessonId(loginUserId,lessonId);
		}
		
		//该课程还没解锁
		if(lessonProgress==null){			
			res.setSuccess(false);
			res.setMessage(UserLessonProMess.ERR_USER_LESSON_LOCK);
			return res;
		}
		else if(loginUser.getType().equals(UserEnums.type.student.getValue())&&
				!lessonProgress.getStatus().equals(UserLessonProgressEnums.status.finish.getValue())
				&& !userId.equals(loginUserId)){				
			res.setSuccess(false);
			res.setMessage(UserLessonProMess.ERR_USER_LESSON_LOCK);
			return res;
		}
		else{
			String oldResourceType=lessonProgress.getResourceType();			
			Lesson lesson=lessonAPI.selectLessonById(lessonId);			
			ResourceDetailDTO resourceDetailDTO=null;	
			Rule rule=null;
			
			//判断课程有没有删除
			if(!lesson.isDel()){
				LessonResourceRuleRelation lesResoRulRel=lessonAPI.selectLessonRelByLessonId(lessonId);	
				if(lesResoRulRel==null){
					//该课程没有配资源
					res.setSuccess(false);
					res.setMessage(LessonMess.ERR_LESSON_RESOURCE_EMPTY);
					respOpenLessonContent.setEmpty(true); 
					return res;
				}
				String lesResRulRelId=lessonProgress.getLessonResourceRuleRelationId();	
				Boolean change=false;
				if(!lesResRulRelId.equals(lesResoRulRel.getId())){
					//关系ID，目前是相等的，后台限制插入课程资源规则关系之后，只能删除，不能修改（所以不会出现就的课程ID关联一个视频，变成课程ID关联一个感想）
					//所以目前不用判断change的业务
					 change=true;
				}				
				//旧的资源类型
				resourceDetailDTO=resourceAPI.selectById(lesResoRulRel.getResourceId());	
				rule=ruleAPI.selectById(lesResoRulRel.getRuleId());
				respOpenLessonContent.setEmpty(false);			
				userLesProBehService.chooseResource(respOpenLessonContent,resourceDetailDTO);
			}else{
				res.setSuccess(false);
				res.setMessage(UserLessonProMess.ERR_END_LESSON_LOST);
				return res;
			}
			
			respOpenLessonContent.setLessonId(lessonId);
			respOpenLessonContent.setResourceType(oldResourceType);

			UserLessonProgress clickLessonProgress=this.selectByUserIdAndLessonId(userId,lessonId);
			String progressStatus =clickLessonProgress.getStatus();
			respOpenLessonContent.setStatus(progressStatus);
			
			if(oldResourceType.equals(CommEnums.resourceType.video.getValue())){
				userLesProBehService.chooseVideo(respOpenLessonContent,resourceDetailDTO,rule,progressStatus,loginUserId);
			}
			else if(oldResourceType.equals(CommEnums.resourceType.music.getValue())){
//				userLesProBehService.chooseMusic(change,respOpenLessonContent,resourceDetailDTO,progressStatus);
			}
			else if(oldResourceType.equals(CommEnums.resourceType.file.getValue())){
//				userLesProBehService.chooseFile(change,respOpenLessonContent,resourceDetailDTO,progressStatus);
			}
			else if(oldResourceType.equals(CommEnums.resourceType.exam.getValue())){
				userLesProBehService.chooseExam(lessonProgress,respOpenLessonContent,resourceDetailDTO,progressStatus);
			}
			else if(oldResourceType.equals(CommEnums.resourceType.thought.getValue())){
				userLesProBehService.chooseThought(respOpenLessonContent,userId,foreignId,progressStatus);
			}
			else if(oldResourceType.equals(CommEnums.resourceType.hwNeedComment.getValue())){
				userLesProBehService.chooseHwNeedComment(lessonProgress,respOpenLessonContent,rule,userId,loginUserId,foreignId,progressStatus);
			}
			else if(oldResourceType.equals(CommEnums.resourceType.hwJustCommit.getValue())){
				userLesProBehService.chooseHwJustCommit(lessonProgress,respOpenLessonContent,rule,userId,loginUserId,foreignId,progressStatus);
			}
			else{
				throw new Exception("类型不存在");
			}				
		}		
		res.setData(respOpenLessonContent);
		res.setSuccess(true);
		return res;
	}


	
	
	@Override
	public UserLessonProgress selectByUserIdAndLessonId(String userId,
			String lessonId) {
		return useLesProMapper.selectByUserIdAndLessonId(userId, lessonId);
	}

	@Override
	public List<UserLessonProgress> findUserLessonProgress(
			UserLessonProgress userLessonProgress) {
		return useLesProMapper.findUserLessonProgress(userLessonProgress);
	}
	
	@Override
	public ResBoolSimpleInfo<Integer> getUserLessonPer(String userId) {
		ResBoolSimpleInfo<Integer> res=new ResBoolSimpleInfo<Integer>();
		User user=userService.selectByPrimaryKey(userId);
		List<String> dataIds=userDataConfigService.findDataIdByUserIdAndType(user.getId(), UserEnums.userDataConfigType.subject.getValue());
		if(CollectionUtils.isEmpty(dataIds)){
			res.setSuccess(false);
			res.setMessage(LessonMess.ERR_EMPTY_SUBJECT);
			return res;
		}
		
		//当前课程
		UserLessonProgress curr=this.getUserCurrLesson(userId, user.getClassId());		
		if(curr.getLessonId().equals(UserLessonProgressCons.END_LESSON_ID1)){
			res.setData(100);
			res.setSuccess(true);			
			return res;
		}
		List<Lesson> lessList=lessonAPI.findLessLesson(user.getClassId(), dataIds.get(0), curr.getSort());
		
		//获取用户一共要学多少节
		List<Lesson> subjectLesson=lessonAPI.findSubjectLesson(user.getClassId(), dataIds.get(0));
		if(subjectLesson.size()==0){
			res.setSuccess(false);
			res.setMessage(LessonMess.ERR_LESSON_EMPTY);
			return res;
		}
				
		int lessCount=lessList.size();
		int total=subjectLesson.size();
		
		double resDou=MathUtils.mul(MathUtils.div(MathUtils.sub(total, lessCount), total, 2), 100);
		int resInt=(int)resDou;
		res.setData(resInt);
		res.setSuccess(true);
		
		return res;
	}
	
	/**
	 * 检查试卷对否
	 * @param myAnswer
	 * @param rightAnsHtml
	 * @return
	 */
	private boolean checkExamQues(List<String> myAnswer,String rightAnsHtml,String questionType){
				
		JSONArray jSONArray=JSON.parseArray(rightAnsHtml);
		List<String> configList=jSONArray.toJavaList(String.class);
		if(questionType.equals(QuestionEnums.questionType.choice.getValue())){
			//选择题排序
			Collections.sort(myAnswer); 
			Collections.sort(configList); 
		}	
		//没配置答案为正确
		if(StringUtils.isEmpty(rightAnsHtml)){
			return true;
		}
		
		if(CollectionUtils.isEmpty(configList)){
			return true;
		}		
		Long emptyNUm=configList.stream().filter(item -> StringUtils.isEmpty(item)).count();	
		if(configList.size()==emptyNUm){
			return true;
		}
		
		
		//先判断个数
		if(myAnswer.size()!=jSONArray.size()){
			return false;
		}
		for(int i=0;i<jSONArray.size();i++){		
			String rightStr=String.valueOf(configList.get(i));
			String my=HtmlUtils.deleteAllHTMLTag(myAnswer.get(i).trim());
			String config=HtmlUtils.deleteAllHTMLTag(rightStr.trim());
			if(!my.trim().equals(config.trim())){
				return false;
			}
		}	
		return true;
	}

	
	public static void main(String[] args) {
		String rightAnsHtml="[\" \",\"\"]";
		JSONArray jSONArray=JSON.parseArray(rightAnsHtml);
		List<String> configList=jSONArray.toJavaList(String.class);
		//没配置答案为正确
		if(StringUtils.isEmpty(rightAnsHtml)){
			System.out.println(1);
		}
		
		if(CollectionUtils.isEmpty(configList)){
			System.out.println(2);
		}		
		Long emptyNUm=configList.stream().filter(item -> StringUtils.isEmpty(item)).count();	
		if(configList.size()==emptyNUm){
			System.out.println(3);
		}
		
	}
	
	
	@Override
	public ResBoolSimpleInfo<UserClassDTO> getUserClass(String classId, String userId) throws Exception {
		ResBoolSimpleInfo<UserClassDTO> res=new ResBoolSimpleInfo<UserClassDTO> ();
		UserClassDTO resDTO=new UserClassDTO();
		LessonClass lessonClass=lessonAPI.findLessonClassById(classId);		
		DefindBeanUtils.copyProperties(lessonClass, resDTO);				
		//用户当前课程
		UserLessonProgress currLesson=this.getUserCurrLesson(userId,classId);	
				
		if(currLesson ==null){
			resDTO.setProgress(0);
			resDTO.setCurrentLesson(null);
			resDTO.setNextLesson(null);
			res.setData(resDTO);
			res.setSuccess(true);
			return res;
		}
		else if(currLesson.getLessonId().equals(UserLessonProgressCons.END_LESSON_ID1)){
			resDTO.setProgress(100);
			resDTO.setCurrentLesson(LessonCons.END_LEAF);
			resDTO.setNextLesson(null);
		}
		else if(null != currLesson) {
			//进行中课程名字
			Lesson lesson = lessonAPI.selectLessonById(currLesson.getLessonId());
			resDTO.setCurrentLesson(lesson.getName());
			//下一节
			String subjectId=userDataConfigService.selectUserSubjectId(userId);	
			String nextLeId = this.getUserNextLesson(classId, userId,subjectId);
			Lesson nLesson = lessonAPI.selectLessonById(nextLeId);
			resDTO.setNextLesson(nLesson.getName());
			
			//进行百分比
			ResBoolSimpleInfo<Integer> per=this.getUserLessonPer(userId);
			if(per.isSuccess()){
				resDTO.setProgress(per.getData());
			}	
		}		
		resDTO.setCurrentLessonId(currLesson.getLessonId());
		resDTO.setResourceType(currLesson.getResourceType());
		
		res.setData(resDTO);
		res.setSuccess(true);
		return res;
	}

	@Override
	public List<UserLessonProgress> findByUserAttr(String userId,
			String classId, String isAttr) {
		return useLesProMapper.findByUserAttr(userId, classId, isAttr);
	}

	@Override
	public UserLessonProgress selectUserEndLesson(String userId,
			String classId, String endLessonId) throws Exception {
		return useLesProMapper.selectUserEndLesson(userId, classId, endLessonId);
	}

	

}